/*
  User: MissingAeon
  Date: 2024/5/20
  Time: 15:40
--*/
import { ChatMessageAddRequest } from "@/api/models/ChatMessageAddRequest.ts";

export type MessageController = {
  send: (message: ChatMessageAddRequest | string) => void;
  receive: (callback: (data: string) => void) => void;
  close: () => void;
};

/**
 * 初始化Socket
 * 创建webSocket连接
 */
function initialSocket(token: string) {
  // socket连接
  const socket = new WebSocket("ws://192.168.2.88:9090/chat/message");

  type Fun = (data: string) => void;
  // 消息接收回调
  const receiveCallback: Fun[] = [];

  socket.addEventListener("open", () => {
    // 在握手阶段添加Authorization头
    socket.send("Bearer " + token);
  });

  socket.addEventListener("message", (event) => {
    console.log("Received:", event.data);
    // 处理接收到的消息
    receiveCallback.forEach((callback) => {
      callback(event.data);
    });
  });

  //close
  socket.addEventListener("close", (e) => {
    console.log("连接关闭->", e);
  });

  //onerror事件监听
  socket.addEventListener("error", (e) => {
    console.log("连接错误->", e);
  });

  /**
   * 发送消息
   * @param message
   */
  function send(message: ChatMessageAddRequest | string) {
    if (typeof message === "string") {
      socket.send(message);
    } else {
      socket.send(JSON.stringify(message));
    }
  }

  /**
   * 接收消息
   * 添加一个接收消息回调
   * @param callback
   */
  function receive(callback: Fun) {
    receiveCallback.push(callback);
  }

  /**
   * 关闭socket连接
   */
  function close() {
    socket.close();
  }

  return { send, receive, close } as MessageController;
}

export default initialSocket;
